/*
 * inter_chip.c
 *
 *  Created on: Oct 1, 2013
 *      Author: Ken Arok
 */

#include <string.h>
#include "io.h"
#include "inter_chip.h"


void vADO_InterChipInit(void)
{
	vIO_Ctrl(IOP_SPI1, IORC_SET_DEFAULT, NULL);
	vIO_Ctrl(IOP_SPI1, IORC_SET_TRANSFER_POLLED, NULL);
}


void vADO_Polling(uint8_t _cmd, void *_pBuf, uint32_t _msgLen)
{
	uint8_t _frame[3];

	_frame[0] = ADO_PROTOCOL_SOH;
	_frame[1] = _cmd;
	_frame[2] = ADO_PROTOCOL_ENQ;

	vIO_Open(IOP_SPI1, 0);
	vIO_Write(IOP_SPI1, (const void *)_frame, 3, IORWF_BYTE_ORDER);
	vIO_Read(IOP_SPI1, _pBuf, _msgLen, IORWF_BYTE_ORDER);
	vIO_Close(IOP_SPI1);
}


uint8_t vADO_Selecting(const void *_msgString, uint32_t _msgLen)
{
	uint8_t _frame[SPI_SIZE_MAX];
	uint8_t _response;

	if(_msgLen < (SPI_SIZE_MAX - 3)) {
		_frame[0] = ADO_PROTOCOL_STX;
		memcpy((void *)(_frame + 1), (const void *)_msgString, _msgLen);
		_msgLen++;
		_frame[_msgLen] = ADO_PROTOCOL_ETX;
		_msgLen++;
		_frame[_msgLen] = 0xA5;
		_msgLen++;

		vIO_Open(IOP_SPI1, 0);
		vIO_Write(IOP_SPI1, (const void *)_frame, _msgLen, IORWF_BYTE_ORDER);
		vIO_Read(IOP_SPI1, &_response, 1, IORWF_BYTE_ORDER);
		vIO_Close(IOP_SPI1);
	}

	return _response;
}


void vADO_EndOfTransmission(void)
{
	const uint8_t _eot = ADO_PROTOCOL_EOT;

	vIO_Open(IOP_SPI1, 0);
	vIO_Write(IOP_SPI1, (const void *)&_eot, 1, IORWF_BYTE_ORDER);
	vIO_Close(IOP_SPI1);
}
